import ConferenceProxy from "./ConferenceProxy";
import { ConnectionFailedError } from "./error";

/**
 * jitsiConnection的增强代理
 * 维持唯一对象conferenceProxy
 * 新增/增强：部分方法
 */
export default class {
    _connectResolve
    _connectReject

    _delegate
    conferenceProxy

    constructor(delegate) {

        this._delegate = delegate
        this.addEventListener(
            JitsiMeetJS.events.connection.CONNECTION_ESTABLISHED,
            () => {
                console.log("connection-success");
                this._connectResolve()
            }
        );
        this.addEventListener(
            JitsiMeetJS.events.connection.CONNECTION_FAILED,
            () => {
                console.log("connection-failed");
                this._connectReject(new ConnectionFailedError("连接失败"))
            }
        );

        this.addEventListener(
            JitsiMeetJS.events.connection.CONNECTION_DISCONNECTED,
            async () => {
                console.log("connection-disconnected");
                await this.conferenceProxy.leave();
            }
        );

    }
    /**
     * 增强:返回jitsi的增强代理对象
     * @returns {ConferenceProxy}
     */
    initJitsiConferenceProxy(name, options) {
        const conference = this.initJitsiConference(name, options);
        this.conferenceProxy = new ConferenceProxy(conference)
        return this.conferenceProxy
    }
    /**
     * 增强:连接服务器，返回promise
     */
    connect(options) {
        const promise = new Promise((resolve, reject) => {
            this._connectResolve = resolve
            this._connectReject = reject
        });
        this._delegate.connect(options);
        return promise
    }
    /**
     * 原装
     */
    initJitsiConference(name, options) {
        return this._delegate.initJitsiConference(name, options)
    }

    /**
     * 原装
     */
    addEventListener(event, listener) {
        this._delegate.addEventListener(event, listener)
    }

}
